#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QString>
#include <QDebug>
#include <QFile>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowFlags(windowFlags()&~Qt::WindowMaximizeButtonHint);
    filePathList = new QStringList;
}

MainWindow::~MainWindow()
{
    delete ui;
    delete filePathList;
}

void MainWindow::on_clearInputBtn_clicked()
{
    QString str = "";
    ui->sourceLineEdt->setText(str);
    ui->targetLineEdt->setText(str);
}

void MainWindow::on_selectFileBtn_clicked()
{
    QFileDialog fileDialog;
    fileDialog.setFileMode(QFileDialog::ExistingFiles);

    if (!fileDialog.exec()) {
        return;
    }

    QStringList temFileList = fileDialog.selectedFiles();
    for (int i = 0; i < temFileList.size(); i++) {
        QString temFile = temFileList[i];
        if (!filePathList->contains(temFile)) {
            filePathList->append(temFile);
        }
    }
    QString pathBrowserText;
    for (int i = 0; i < filePathList->size(); i++) {
        QString filePath = filePathList->at(i);
        QString prefix = "第" + QString::number(i + 1) + "行：";
        filePath.prepend(prefix);
        pathBrowserText.append(filePath).append("\n");
    }

    ui->pathBrowser->setText(pathBrowserText);
}

void MainWindow::on_clearFileBtn_clicked()
{
    QString str = "";
    filePathList->clear();
    ui->pathBrowser->setText(str);
}

void MainWindow::on_executeBtn_clicked()
{
    if (filePathList->empty()) {
        QMessageBox::warning(this, "提示框", "未选择文件");
        return;
    }
    QString sourceTxt = ui->sourceLineEdt->text();
    QString targetTxt = ui->targetLineEdt->text();
    for (int i = 0; i < filePathList->size(); i++) {
        QString filePath = filePathList->at(i);
        QFile file(filePath);
        if (!file.exists()) {
            continue;
        }
        QString fileName = file.fileName();
        file.rename(fileName.replace(sourceTxt, targetTxt));
    }
    QMessageBox::information(this, "提示框", "批量改名完成");
}
